<template>
  <div class="upload-box">
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :limit="limit"
      :on-preview="handlePictureCardPreview"
      :class="{disabled: fileComputed }"
      :on-remove="handleRemove"
      :http-request="upload"
      :on-change="handleChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog width="600px" top="8vh" title="图片预览" :visible="dialogVisible" @update:visible="dialogVisible = $event">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!-- <el-progress v-show="showPercent" :percentage="percent" style="width: 180px" /> -->
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKIDkT3W9f2EF5iAPTM0Zu44tUrzrUt666qM', // 身份识别ID
  SecretKey: 'PbYFfspXzEdpnbDdolUxA7oHertocEcl'// 身份秘钥
})
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      showPercent: false,
      percent: 0,
      fileList: [
        // { name: 'food.jpeg', url: 'https://tangxiaotang103-1315920946.cos.ap-shanghai.myqcloud.com/jirounan.gif' }
      ],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length >= this.limit
    },
    // 判断是否所有图片上传成功
    uploadAllSuccess() {
      return this.fileList.length > 0 && this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 删除图片
    // file 文件
    // fileList 删除后的文件列表
    // this.fileList 数据中的文件列表
    handleRemove(file, fileList) {
    //   console.log(file, fileList)
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    //   this.fileList = [...fileList]
    },
    // 添加文件，有文件预览
    // 文件状态改变时，无论成功或失败都会被调用
    handleChange(file, fileList) {
      console.log(fileList)
      this.fileList = [...fileList]
    },
    // 上传操作
    upload(params) {
    //   console.log(params.file)
    // console.log(params.file)
      if (!params.file) return
      const fileObj = this.fileList.find(item => item.uid === params.file.uid)
      this.showPercent = true
      // 执行上传操作
      cos.putObject({
        Bucket: 'tangxiaotang103-1315920946', /* 存储桶 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData))
          const percent = parseInt(progressData.percent * 100)
          fileObj.status = 'uploading'
          fileObj.percentage = percent
          this.percent = percent
        }
      }, (err, data) => {
        //   console.log(err || data)
        //   console.log(data)
        if (err) console.dir(err)
        if (data.statusCode === 200) {
          // 找到对应上传的file文件
          // const fileObj = this.fileList.find(item => item.uid === params.file.uid)
          // console.log(fileObj)
          // 更新状态
          fileObj.status = 'success'
          // 修改地址
          fileObj.url = 'https://' + data.Location
        }
        // console.log(data)
        // setTimeout(() => {
        //   this.showPercent = false
        //   this.percent = 0
        // }, 500)
      })
    },
    // 配置上传前的校验, 只要通过校验, 才能进行上传
    beforeUpload(file) {
      // 1. 限制文件类型 file.type
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 2) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    }
  }
}
</script>

<style scoped lang="scss">
 .disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
